package com.xyc.gulimall.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyc.common.constant.OrderStatusEnum;
import com.xyc.common.exception.NoStockException;
import com.xyc.common.to.mq.OrderTo;
import com.xyc.common.to.mq.SeckillOrderTo;
import com.xyc.common.utils.PageUtils;
import com.xyc.common.utils.Query;
import com.xyc.common.utils.R;
import com.xyc.common.vo.MemberResponseVo;
import com.xyc.gulimall.order.constant.OrderConstant;
import com.xyc.gulimall.order.dao.OrderDao;
import com.xyc.gulimall.order.entity.OrderEntity;
import com.xyc.gulimall.order.entity.OrderItemEntity;
import com.xyc.gulimall.order.entity.PaymentInfoEntity;
import com.xyc.gulimall.order.feign.CartFeignService;
import com.xyc.gulimall.order.feign.MemberFeignService;
import com.xyc.gulimall.order.feign.ProductFeignService;
import com.xyc.gulimall.order.feign.WmsFeignService;
import com.xyc.gulimall.order.interceptor.LoginUserInterceptor;
import com.xyc.gulimall.order.service.OrderItemService;
import com.xyc.gulimall.order.service.OrderService;
import com.xyc.gulimall.order.service.PaymentInfoService;
import com.xyc.gulimall.order.vo.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private final ThreadLocal<OrderSubmitVo> orderSubmitVoThreadLocal = new ThreadLocal<>();

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private CartFeignService cartFeignService;

    @Autowired
    private WmsFeignService wmsFeignService;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
        System.out.println("memberResponseVo:" + memberResponseVo);
        System.out.println("主线程..." + Thread.currentThread().getId());

        //获取之前的请求
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        System.out.println("requestAttributes:" + requestAttributes);

        //1、远程查询所有的收货地址列表
        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            System.out.println("memberFeignService线程..." + Thread.currentThread().getId());
            //每一个线程都来共享之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);

            List<MemberAddressVo> addressVos = memberFeignService.getAddress(memberResponseVo.getId());
            orderConfirmVo.setAddressVos(addressVos);
        }, threadPoolExecutor);

        //2、远程查询购物车所有选中的购物项
        CompletableFuture<Void> getCartCheckFuture = CompletableFuture.runAsync(() -> {
            System.out.println("cartFeignService线程..." + Thread.currentThread().getId());
            //每一个线程都来共享之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);

            List<OrderItemVo> Items = cartFeignService.getCurrentUserCartItems();
            orderConfirmVo.setItemVos(Items);
        }, threadPoolExecutor).thenRunAsync(
                // 3、远程查询所选的购物项是否有库存
                () -> {
                    System.out.println("thenRunAsync线程..." + Thread.currentThread().getId());
                    //每一个线程都来共享之前的请求数据
                    RequestContextHolder.setRequestAttributes(requestAttributes);

                    List<OrderItemVo> itemVos = orderConfirmVo.getItemVos();
                    List<Long> skuIdList = itemVos.stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());

                    R r = wmsFeignService.getSkusHasStock(skuIdList);
                    List<SkuHasStockVo> skuHasStockVo = JSON.parseArray(JSON.toJSONString(r.get("data")), SkuHasStockVo.class);
                    if (skuHasStockVo != null) {
                        Map<Long, Boolean> collect = skuHasStockVo.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
                        orderConfirmVo.setStocks(collect);
                    }
                }, threadPoolExecutor);

        /**
         * feign在远程调用之前会构造请求，调用很多的拦截器：
         * RequestTemplate interceptor : requestInterceptor
         */

        //3、查询用户积分
        Integer integration = memberResponseVo.getIntegration();
        orderConfirmVo.setIntegration(integration);

        //4、其他数据自动计算
        orderConfirmVo.setTotal(orderConfirmVo.getTotal());
        orderConfirmVo.setPayPrice(orderConfirmVo.getPayPrice());

        // TODO 5、防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        stringRedisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId(), token, 30, TimeUnit.MINUTES);
        orderConfirmVo.setOrderToken(token);

        CompletableFuture.allOf(getAddressFuture, getCartCheckFuture).get();

        return orderConfirmVo;
    }

    //本地事务，在分布式系统下，只能控制自己的回滚，控制不了其它服务的回滚。
    //分布式事务，最大原因：网络问题+分布式机器。
//    @GlobalTransactional  //高并发
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo orderSubmitVo) {
        SubmitOrderResponseVo submitOrderResponseVo = new SubmitOrderResponseVo();
        orderSubmitVoThreadLocal.set(orderSubmitVo);
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
        submitOrderResponseVo.setCode(0);
        //1、验证令牌【令牌的对比和删除必须保证原子性：lua脚本】
        //脚本返回0(令牌失败)或1(删除成功)
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        String orderToken = orderSubmitVo.getOrderToken();
        //原子验证令牌和删除令牌
        Long result = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId()), orderToken);
        if (result == 0L) {
            //令牌验证失败
            submitOrderResponseVo.setCode(1);
            return submitOrderResponseVo;
        } else {
            //令牌验证成功
            //下单：去创建订单、验令牌、验价格、锁库存...
            //1、创建订单、订单项等信息
            OrderCreateTo order = createOrder();
            //2、验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = orderSubmitVo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                //金额对比成功
                // TODO 3、保存订单
                saveOrder(order);
                //4、锁库存，只要有异常就回滚订单数据。
                //订单号、所有订单项信息（skuId、skuName、num）
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(order.getOrder().getOrderSn());

                List<OrderItemVo> orderItemVos = order.getOrderItems().stream().map(item -> {
                    OrderItemVo itemVo = new OrderItemVo();
                    itemVo.setSkuId(item.getSkuId());
                    itemVo.setCount(item.getSkuQuantity());
                    itemVo.setTitle(item.getSkuName());
                    return itemVo;
                }).collect(Collectors.toList());
                wareSkuLockVo.setLocks(orderItemVos);

                // TODO 4、远程锁库存 假失败
                //库存成功了，但是网络原因超时了，导致订单回滚，库存不滚

                //为了保证高并发。库存服务自己回滚。可以发消息mq给库存服务；
                //库存本身也可以使用自动解锁模式   消息队列
                R r = wmsFeignService.orderLockStock(wareSkuLockVo);
                if (r.getCode() == 0) {
                    //锁库存成功
                    submitOrderResponseVo.setOrder(order.getOrder());

                    // TODO 5、远程扣减积分 出异常
//                    int i = 10 / 0; //订单回滚，库存不滚
                    // TODO 订单创建成功，发送消息给MQ
                    rabbitTemplate.convertAndSend(
                            "order-event-exchange",
                            "order.create.order",
                            order.getOrder()
                    );
                    return submitOrderResponseVo;
                } else {
                    //锁库存失败
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                }

            } else {
                submitOrderResponseVo.setCode(2);
                return submitOrderResponseVo;
            }
        }
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));

    }

    @Override
    public void closeOrder(OrderEntity orderEntity) {
        //关闭订单之前先查询当前这个订单的最新状态
        OrderEntity entity = this.getById(orderEntity.getId());
        if (entity.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())) {
            //关单
            OrderEntity update = new OrderEntity();
            update.setId(orderEntity.getId());
            update.setStatus(OrderStatusEnum.CANCELED.getCode());
            this.updateById(update);

            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(entity, orderTo);
            //发给mq一个
            try {
                // TODO 保证消息一定会发送出去，每一个消息都可以做好日志记录(给数据库保存每一个消息的详细信息)。
                // TODO 定期扫描数据库，将失败的消息再发送一遍。
                rabbitTemplate.convertAndSend(
                        "order-event-exchange",
                        "order.release.other",
                        orderTo
                );
            } catch (Exception e) {
                // TODO 将没发送成功的消息进行重试发送。

            }
        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity orderEntity = this.getOrderByOrderSn(orderSn);

        payVo.setTotal_amount(orderEntity.getPayAmount().setScale(2, BigDecimal.ROUND_UP).toString());
        payVo.setOut_trade_no(orderSn);
        payVo.setSubject("谷粒商城");

        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberResponseVo.getId())
                        .orderByDesc("id")
        );
        List<OrderEntity> collect = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(itemEntities);
            return order;
        }).collect(Collectors.toList());

        page.setRecords(collect);

        return new PageUtils(page);
    }

    /**
     * 处理支付宝的处理结果
     *
     * @param vo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVo vo) throws ParseException {
        //1、保存交易流水
        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
        paymentInfoEntity.setAlipayTradeNo(vo.getTrade_no());
        paymentInfoEntity.setOrderSn(vo.getOut_trade_no());
        paymentInfoEntity.setPaymentStatus(vo.getTrade_status());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        paymentInfoEntity.setCallbackTime(sdf.parse(vo.getNotify_time()));

        paymentInfoService.save(paymentInfoEntity);

        //2、修改订单的状态信息
        if (vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED")) {
            //支付成功状态
            String outTradeNo = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(outTradeNo, OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrderTo) {
        // TODO 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrderTo.getOrderSn());
        orderEntity.setMemberId(seckillOrderTo.getMemberId());

        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());

        BigDecimal multiply = seckillOrderTo.getSeckillPrice().multiply(new BigDecimal(seckillOrderTo.getNum().toString()));
        orderEntity.setPayAmount(multiply);

        this.save(orderEntity);

        // TODO 保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(seckillOrderTo.getOrderSn());
        orderItemEntity.setRealAmount(multiply);

        orderItemEntity.setSkuQuantity(seckillOrderTo.getNum());

        // TODO 获取当前sku的详细信息进行设置
        R r = productFeignService.getSpuInfoBySkuId(seckillOrderTo.getSkuId());

        orderItemService.save(orderItemEntity);
    }

    /**
     * 保存订单数据
     *
     * @param order 订单
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }

    private OrderCreateTo createOrder() {
        OrderCreateTo orderCreateTo = new OrderCreateTo();

        //1、生成订单号
        String orderSn = IdWorker.getTimeId();
        OrderEntity orderEntity = buildOrder(orderSn);

        //2、获取到所有的订单项
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderSn);

        //3、计算价格相关、验价
        computePrice(orderEntity, orderItemEntities);

        orderCreateTo.setOrder(orderEntity);
        orderCreateTo.setOrderItems(orderItemEntities);

        return orderCreateTo;
    }

    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        BigDecimal total = new BigDecimal("0.0");

        BigDecimal coupon = new BigDecimal("0.0"),
                integration = new BigDecimal("0.0"),
                promotion = new BigDecimal("0.0");
        Integer gift = 0, growth = 0;
        //订单的总额，叠加每一个订单项的总额信息
        for (OrderItemEntity orderItemEntity : orderItemEntities) {
            coupon = coupon.add(orderItemEntity.getCouponAmount());
            integration = integration.add(orderItemEntity.getIntegrationAmount());
            promotion = promotion.add(orderItemEntity.getPromotionAmount());
            total = total.add(orderItemEntity.getRealAmount());

            gift += orderItemEntity.getGiftIntegration();
            growth += orderItemEntity.getGiftGrowth();
        }
        //1、订单价格、积分等相关
        orderEntity.setTotalAmount(total);
        //应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setCouponAmount(coupon);

        //设置积分等信息
        orderEntity.setIntegration(gift);
        orderEntity.setGrowth(growth);
        orderEntity.setDeleteStatus(0);//未删除
    }

    private OrderEntity buildOrder(String orderSn) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberId(LoginUserInterceptor.loginUser.get().getId());
        //获取收货地址信息
        OrderSubmitVo orderSubmitVo = orderSubmitVoThreadLocal.get();
        R fare = wmsFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareVo = JSON.parseObject(JSON.toJSONString(fare.get("data")), FareVo.class);
        //设置收货人信息
        System.out.println("fareVo" + fareVo);
        orderEntity.setFreightAmount(fareVo.getFare());
        orderEntity.setReceiverCity(fareVo.getAddress().getCity());
        orderEntity.setReceiverDetailAddress(fareVo.getAddress().getDetailAddress());
        orderEntity.setReceiverName(fareVo.getAddress().getName());
        orderEntity.setReceiverPhone(fareVo.getAddress().getPhone());
        orderEntity.setReceiverPostCode(fareVo.getAddress().getPostCode());
        orderEntity.setReceiverProvince(fareVo.getAddress().getProvince());
        orderEntity.setReceiverRegion(fareVo.getAddress().getRegion());

        //设置订单的相关状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);

        return orderEntity;
    }

    /**
     * 构建所有订单项数据
     *
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //最后确定每个购物项的价格
        List<OrderItemVo> userCartItems = cartFeignService.getCurrentUserCartItems();
        if (userCartItems != null && !userCartItems.isEmpty()) {
            return userCartItems.stream().map(cartItem -> {
                OrderItemEntity orderItemEntity = buildOrderItem(cartItem);

                orderItemEntity.setOrderSn(orderSn);

                return orderItemEntity;
            }).collect(Collectors.toList());
        }
        return null;
    }

    /**
     * 构建某一个订单项
     *
     * @param cartItem
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //1、订单信息：订单号
        //2、商品的spu信息
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuInfoVo = JSON.parseObject(JSON.toJSONString(r.get("data")), SpuInfoVo.class);
        orderItemEntity.setSpuId(spuInfoVo.getId());
        orderItemEntity.setSpuBrand(spuInfoVo.getBrandId().toString());
        orderItemEntity.setSpuName(spuInfoVo.getSpuName());
        orderItemEntity.setCategoryId(spuInfoVo.getCatalogId());

        //3、商品的sku信息
        orderItemEntity.setSkuId(cartItem.getSkuId());
        orderItemEntity.setSkuName(cartItem.getTitle());
        orderItemEntity.setSkuPic(cartItem.getImage());
        orderItemEntity.setSkuPrice(cartItem.getPrice());
        orderItemEntity.setSkuAttrsVals(StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";"));
        orderItemEntity.setSkuQuantity(cartItem.getCount());
        //4、优惠信息（不做）
        //5、积分信息
        orderItemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        orderItemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        //6、订单项的价格信息
        orderItemEntity.setPromotionAmount(new BigDecimal("0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0"));
        orderItemEntity.setIntegrationAmount(new BigDecimal("0"));
        //当前订单项的实际金额
        BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        //减去优惠卷...
        BigDecimal subtract = origin.subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(subtract);

        return orderItemEntity;
    }
}